//
//  SpieleViewController.m
//  Lextra Junior ueb IT
//
//  Created by Dirk Lieder on 27.05.11.
//  Copyright 2011 Phosphon. All rights reserved.
//
#define RGB(r, g, b) \
[UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#import "SpieleViewController.h"
#import "Lextra_Engine.h"
#import "NavigationViewController.h"
#import "AsyncImageView.h"

#import "Lextra_Engine.h"

//ADDED BY LDHAI
#import "Global.h"

@implementation SpieleViewController

@synthesize myTableView;
//__NGUYEN_HUY_SON____________________________________________________________________________________
@synthesize spieleSplitview;
@synthesize tabBarController;
@synthesize woerView;

//______________________________________________________________________________________

static NSMutableArray *listData; // list


- (void)setDelegate:(id)new_delegate{
	Delegate = new_delegate;
}
// akt display
- (void)aktDisplay{
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    bIsSelectSpiele1 = FALSE;
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    } 
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        CGFloat navBarHeight = 44.0f;    
        CGRect frame = CGRectMake(self.navigationController.navigationBar.frame.origin.x, self.navigationController.navigationBar.frame.origin.y, self.navigationController.navigationBar.frame.size.width, navBarHeight);
        [self.navigationController.navigationBar setFrame:frame];

        self.contentSizeForViewInPopover = CGSizeMake(310, self.myTableView.rowHeight*10.0);
        //__NGUYEN_HUY_SON___
        
        UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_table_spiele"]];
        [self.navigationController.navigationBar addSubview:imageView1];
        [imageView1 release];
        
        [self.navigationController.navigationBar setBackgroundColor:[[UIColor alloc] initWithRed:134 green:166 blue:228 alpha:1.0]];
        
        nsInterSelect = 1;
        spiele1 = [[Spiel1ViewController alloc] initWithNibName:@"Spiele1-iPad" bundle:nil];
        
        NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, spiele1, nil];
        spieleSplitview.viewControllers = viewControllers;
        spiele1.woerView = woerView;
        [spiele1 setDelegatePlud:self]; 
        
//        if (spieleSplitview.barButton != nil) {
//            [spiele1 showRootPopoverButtonItem:spieleSplitview.barButton];
//        }
        [viewControllers release];

    }

    // Build the array static  
    listData = [[NSMutableArray alloc] init];
    
	[listData addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"game", @"typ",@"Hör mal!" , @"name", @"Höre genau hin und finde das richtige Wort!", @"beschreibung", @"hoermal", @"bild", @"31", @"target", nil]];
	[listData addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"game", @"typ",@"Wortsammler" , @"name", @"Finde zu den Wörtern die passenden Bilder!", @"beschreibung", @"wortsammler", @"bild", @"32", @"target", nil]];
	[listData addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"game", @"typ",@"Vokabeltrainer" , @"name", @"Mach dich fit in Vokabeln - in beide Richtungen!", @"beschreibung", @"vokabeltrainer", @"bild", @"33", @"target", nil]];
	[listData addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"game", @"typ",@"Sprach-Memo" , @"name", @"Suche die passenden Paare aus Bild und Sprache!", @"beschreibung", @"sprachmemo", @"bild", @"34", @"target", nil]];
	[listData addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"game", @"typ",@"Schnellübersetzer" , @"name", @"Wie schnell findest du das richtige Wort?", @"beschreibung", @"schnelluebersetzer", @"bild", @"35", @"target", nil]];
    
    // Show the string values  
    // for (NSString *str in listData)
    //    NSLog(@"--%@", str);
    
    [myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [myTableView reloadData];
 
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}



#pragma mark - tableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
    return 78;			
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [listData count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	
	NSUInteger row = [indexPath row];
	UITableViewCell *cell;
	
	static NSString *CustomCellIdentifier;
    
    // Eintrag
    CustomCellIdentifier = @"part1";
    cell = [tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
    if (cell == nil) {
        // new cell
        cell = [self getCell:CustomCellIdentifier];
    }
    
    NSDictionary *Pointer = [listData objectAtIndex:row];
    //__NGUYEN_HUY_SON__________________________________________________________________________________
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        cell.backgroundColor = [UIColor colorWithRed:172.0/255.0 green:173.0/255.0 blue:175.0/255.0 alpha:1.0];
    }
    //___END_NGUYEN_HUY_SON_____________________________________________________________________________________
    UILabel *descriptionLabel = (UILabel*)[cell.contentView viewWithTag:1];
    
    
    NSMutableString *tmpString1 = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"name"]];
    NSMutableString *tmpString2 = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"beschreibung"]];
    //NSLog(@"laenge *%@", tmpString1);
            
    descriptionLabel.frame = CGRectMake(100, 10, 195, 50);
    descriptionLabel.text = tmpString1;

    CGSize expectedLabelSize = [descriptionLabel.text sizeWithFont:descriptionLabel.font 
                                                 constrainedToSize:descriptionLabel.frame.size
                                                     lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel.frame = CGRectMake(100, 10, 195, expectedLabelSize.height);
    
   
    
    UILabel *descriptionLabel2 = (UILabel*)[cell.contentView viewWithTag:2];    

    descriptionLabel2.frame = CGRectMake(100, 10, 195, 50);
    descriptionLabel2.text = tmpString2;

    CGSize expectedLabelSize2 = [descriptionLabel2.text sizeWithFont:descriptionLabel2.font 
                                                   constrainedToSize:descriptionLabel2.frame.size
                                                       lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel2.frame = CGRectMake(100, 10, 195, expectedLabelSize2.height);
    descriptionLabel2.center = CGPointMake(descriptionLabel2.center.x, descriptionLabel.bounds.size.height+10 + descriptionLabel2.bounds.size.height/2  );
    
    
    [tmpString1 release];
    [tmpString2 release];
   
    AsyncImageView *descriptionImage = (AsyncImageView*)[cell.contentView viewWithTag:3];
        
    NSString *myName = [Pointer objectForKey:@"bild"];
                               
    NSString *substring;
    if([myName length] > 2){
        if([myName hasSuffix:@".tif"]){
            substring = [[myName substringToIndex:[myName length]-4] stringByAppendingString:@"_k"];
        } else {
            substring = [myName stringByAppendingString:@"_k"];
        }
    } else {
        substring = [[NSString alloc] initWithString:@"pirat_k"];
    }
    //NSLog(@"laenge *%@*%d", myName,[myName length]);
    
    [descriptionImage asyncImageLoad:substring];
    
    return cell;
}



#pragma mark -
#pragma mark Table Delegate Methods 


-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath; 
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSInteger row = [indexPath row];
    
    NSDictionary *infoArray = (NSDictionary*)[listData objectAtIndex:row];
    //__NGUYEN_HUY_SON____________________________________________________________________________
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) //Neu iPad
    {
        NSInteger theScreen = [[infoArray objectForKey:@"target"] intValue];
        // Dismiss the popover if it's present.
        if (spieleSplitview.pc != nil) 
        {
            [spieleSplitview.pc dismissPopoverAnimated:YES];
        }
        if (nsInterSelect == 5) {
            [spiele5 sstop];
            [spiele5 release];
        }
        if (nsInterSelect == 4) {
            [spiele4 sstop];
            [spiele4 release];
        }
        if (nsInterSelect == 1) {
            [spiele1 release];
        }
        if (nsInterSelect == 2) {
            [spiele2 release];
        }
        if (nsInterSelect == 3) {
            [spiele3 release];
        }
        if (theScreen == 31) 
        {
            nsInterSelect = 1;
            spiele1 = [[Spiel1ViewController alloc] initWithNibName:@"Spiele1-iPad" bundle:nil];

            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, spiele1, nil];
            spieleSplitview.viewControllers = viewControllers;
            spiele1.woerView = woerView;
            [spiele1 setDelegatePlud:self]; 

            if (spieleSplitview.barButton != nil) {
                [spiele1 showRootPopoverButtonItem:spieleSplitview.barButton];
            }
            [viewControllers release];
        }
        if(theScreen == 32)
        {
            nsInterSelect = 2;
            spiele2 = [[Spiel2ViewController alloc] initWithNibName:@"Spiele2-iPad" bundle:nil];
            
            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, spiele2, nil];
            spieleSplitview.viewControllers = viewControllers;
            spiele2.woerView = woerView;
            [spiele2 setDelegatePlud:self]; 
            
            if (spieleSplitview.barButton != nil) {
                [spiele2 showRootPopoverButtonItem:spieleSplitview.barButton];
            }
            
            [viewControllers release];
        }
        if(theScreen == 33)
        {
            nsInterSelect = 3;

            spiele3 = [[Spiel3ViewController alloc] initWithNibName:@"Spiele3-iPad" bundle:nil];
            spiele3.woerView = woerView;
            
            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, spiele3, nil];
            spieleSplitview.viewControllers = viewControllers;
            
            [spiele3 setDelegatePlud:self]; 
            if (spieleSplitview.barButton != nil) {
                [spiele3 showRootPopoverButtonItem:spieleSplitview.barButton];
            }
            [viewControllers release];
        }
        if (theScreen == 34) {
            nsInterSelect = 4;

            spiele4 = [[Spiel4ViewController alloc] initWithNibName:@"spiele4-iPad" bundle:nil];
            spiele4.woerView = woerView;
            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, spiele4, nil];
            spieleSplitview.viewControllers = viewControllers;
            if (spieleSplitview.barButton != nil) {
                [spiele4 showRootPopoverButtonItem:spieleSplitview.barButton];
            }
            [spiele4 setDelegatePlud:self];
            [viewControllers release];
 
        }
        if (theScreen == 35) {
            spiele5 = [[Spiel5ViewController alloc] initWithNibName:@"Spiel5ViewController-iPad" bundle:nil];
            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, spiele5, nil];
            spiele5.woerView = woerView;
            spieleSplitview.viewControllers = viewControllers;
            [spiele5 setDelegatePlud:self];
            if (spieleSplitview.barButton != nil) {
                [spiele5 showRootPopoverButtonItem:spieleSplitview.barButton];
            }
            [viewControllers release];
            nsInterSelect= 5;
        }
        
    }//___END_NGUYEN_HUY_SON__________________________________________________________________________________
    else
    {
        [(Lextra_Engine*)Delegate goScreen:[[infoArray objectForKey:@"target"] intValue] theName:@"a..c" thePara:NULL deliteView:false];
    }
    //__NGUYEN_HUY_SON_END____________________________________________________________________________________
    if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) 
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

}


#pragma mark -
#pragma mark cell creation 
-(UITableViewCell*)getCell:(NSString*)myIdentifier{
	
	// new cell
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myIdentifier] autorelease];
    cell.userInteractionEnabled = YES;
    cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Empty.png"]] autorelease];
    cell.selectedBackgroundView.autoresizingMask = UIViewContentModeScaleToFill;
	
	// Text Label blue
	CGRect aframe = CGRectMake(100, 0, 195, 50);
	UILabel *textLabel = [[[UILabel alloc] initWithFrame:aframe] autorelease];
	
    textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:14];
	textLabel.numberOfLines=0;
    textLabel.lineBreakMode = UILineBreakModeWordWrap;
    textLabel.textColor = RGB(0xff, 0x33, 0x33);
    textLabel.highlightedTextColor = RGB(0xa0, 0x00, 0x00);
	textLabel.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
	textLabel.clearsContextBeforeDrawing = YES;
	textLabel.tag = 1;
    //textLabel.frame = CGRectMake(100, 10, 195, 50);
	[cell.contentView addSubview:textLabel];		
    
 	// Text Label blak
	aframe = CGRectMake(100, 0, 195, 50);
	textLabel = [[[UILabel alloc] initWithFrame:aframe] autorelease];
	
    textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Italic" size:14];
	textLabel.numberOfLines=0;
    textLabel.lineBreakMode = UILineBreakModeWordWrap;
    textLabel.textColor = RGB(0x00, 0x00, 0x00);
    textLabel.highlightedTextColor = RGB(0x60, 0x60, 0x60);
	textLabel.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
	textLabel.clearsContextBeforeDrawing = YES;
	textLabel.tag = 2;
    //textLabel.frame = CGRectMake(100, 10, 195, 50);
	[cell.contentView addSubview:textLabel];		
    
    // image view async
    aframe = CGRectMake(5, 0, 90,75);
    //__NGUYEN_HUY_SON___
    AsyncImageView *topImageView;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        topImageView = [[AsyncImageView alloc] initWithFrame:aframe];
    }
    else
    {
        topImageView = [[[AsyncImageView alloc] initWithFrame:aframe] autorelease];
    }
    //___END_NGUYEN_HUY_SON___
    topImageView.tag = 3;
    topImageView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
    [cell.contentView addSubview:topImageView];	
	
    
	// trenner
	CGRect frame = CGRectMake(0, 77, 320,1);
	UIImageView *trennerImageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"listtrenner.png"]] autorelease];
	trennerImageView.frame = frame;
	[cell.contentView addSubview:trennerImageView];
    
    
	cell.contentView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
    
	return cell;
}




- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//__NGUYEN_HUY_SON__________________________________________________________________________________
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        return YES;
    }
    else
    {
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
}
//___END_NGUYEN_HUY_SON_____________________________________________________________________________________

//_______________NGUYEN_HUY_SON___________________________________________________
- (void)splitViewController:(UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController:(UIPopoverController*)pc {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        // Keep references to the popover controller and the popover button, and tell the detail view controller to show the button.
        barButtonItem.title = @"Spiele";
        spieleSplitview.pc = pc;
        spieleSplitview.barButton = barButtonItem;
        UIViewController <SubstitutableDetailViewController> *detailViewController = [spieleSplitview.viewControllers objectAtIndex:1];
        [detailViewController showRootPopoverButtonItem:spieleSplitview.barButton];
        
        //ADDED BY LDHAI
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar3-portrait.png"]];
        
        if([currentViewController isEqualToString:@"Woerter"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar1-portrait.png"]];
        }
        else if ([currentViewController isEqualToString:@"Themen"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar2-portrait.png"]];
        }
        else if ([currentViewController isEqualToString:@"Spiele"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar3-portrait.png"]];
        }
        else
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar4-portrait.png"]];
        }
        
        //UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar3-portrait.png"]];
        [self.tabBarController.tabBar addSubview:imageView];
        [imageView release];
    }
}

- (void)splitViewController:(UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        // Nil out references to the popover controller and the popover button, and tell the detail view controller to hide the button.
        UIViewController <SubstitutableDetailViewController> *detailViewController = [spieleSplitview.viewControllers objectAtIndex:1];
        [detailViewController invalidateRootPopoverButtonItem:spieleSplitview.barButton];
        spieleSplitview.pc = nil;
        spieleSplitview.barButton = nil;
        
        //ADDED BY LDHAI
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar3.png"]];
        
        if([currentViewController isEqualToString:@"Woerter"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar1.png"]];
        }
        else if ([currentViewController isEqualToString:@"Themen"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar2.png"]];
        }
        else if ([currentViewController isEqualToString:@"Spiele"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar3.png"]];
        }
        else
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar4.png"]];
        }
        
        //UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar3.png"]];
        [self.tabBarController.tabBar addSubview:imageView];
        [imageView release];
    }
}
//_______END_NGUYEN_HUY_SON______________________________________________________________________________________
@end
